//
//  AppDelegateEx.swift
//  YPWatermarkCamera
//
//  Created by 赵新 on 2022/5/12.
//

import Foundation
import YPNetwork

#if canImport(WmcLogin)
import WmcLogin
#endif

extension AppDelegate {
    func configWatermark() {
        // 注册平台
        YPWmcManager.shared.platform = .watermarkCamera
        YPWmcManager.loadConfig()
        YPWmcManager.shared.delegate.loginDelegate = self
        configYPLoginManager()
    }

    func configYPLoginManager() {
        #if canImport(WmcLogin)
        let host = WmcLoginManager.loginHost()
        guard let hostURL = URL(string: host) else { return }
        YPLoginManager.shared.requestBaseUrl = hostURL
        var header: [String: String] = WmcNetworkField.clientInfo
        header["package_name"] = "gcdkxj"
        YPLoginManager.shared.requestHeaders = header
        YPLoginManager.shared.appName = "鱼泡水印相机"
        YPLoginManager.shared.showCloseBtn = true
        YPLoginManager.shared.privacyAgreementUrl = WmcCameraSettingVM.PrivacyAgreement.urlStr
//        YPLoginManager.shared.manualExit = true
        YPLoginManager.shared.dismissBlock = {
            // 是否被挤掉（默认为false）
            if !YPLoginManager.shared.isSqueezedOut {
                YPGCD.Delay(delay: 0.6) {
                    if let currentVC = YPApp.CurrentVC {
                        currentVC.popToSpecificVC(vcClass: WmcHomeVC.classForCoder())
                    }
                }
            }
        }
        
        // 监听网络状态
        YPNetworkReachability.monitoring().subscribe(onNext: { [weak self] type in
            guard let weakSelf = self else { return }
            switch type {
            case .ethernetOrWiFi, .cellular:
                let secret =
                    """
                    3l+c3lzFdo/5iJGW0a39pm/AHexi2bMlFPUcDLFmm9tfuhrltZE5Fvc+dZKdN8KHml8emcjmrbVxLYTNCU+Gryk0cvcKsIcp0LnzNCnmei3uxqF+FlCHtUZRzHhfEQ0JEDyt+uH+dor1Y9yVC+WHxZW3fQtFmTgqj8nN4E6nN6BWVTlG5m2w1kq9gN6MDcS36DOqLLWWLayFJ/wgaDkePrfq7o4CYIS1cho7cPVz65ymyOahct3FZmIo2n/43hD7
                    """
                YPLoginManager.shared.setVerifySDKSecret(secret)
            default: break
            }
        }).disposed(by: rx.disposeBag)
        #endif
    }
}

// MARK: - AppDelegate + WmcLoginDelegate

extension AppDelegate: WmcLoginDelegate {
    /// 需要登录
    func loginNeed(_ attribute: WmcAttribute, animated: Bool, success: YPBlock.Empty? = nil, failure: YPBlock.Empty? = nil) {
        #if canImport(WmcLogin)
            YPLoginManager.shared.oneClickLogin { userInfo in
                var params: [String: String] = [:]
                params["uid"] = userInfo.userId
                params["uuid"] = userInfo.uuid
                params["token"] = userInfo.token
                params["singletoken"] = userInfo.singleSignToken
                params["userId"] = userInfo.userId
                params["userName"] = userInfo.userName
                params["nickName"] = userInfo.nickName
                params["phone"] = userInfo.phone
                params["userType"] = userInfo.userType.info.value
                params["errcode"] = userInfo.errcode

                WmcLoginManager.shared.fetchWmcUserInfo(userInfo: params, silent: false) {
//                    YPApp.CurrentVC?.navigationController?.dismiss(animated: false, completion: {
                        success?()
//                    })
                } failure: { error in
                    let msg = error?.localizedDescription ?? "登录失败"
                    WmcHudManager.toast(msg)
                    failure?()
                }
            }
        #endif
    }

    /// 登录失效
    func loginInvalid(_ attribute: WmcAttribute, data: Any?, code: Int64, message: String?) {
        WmcLoginManager.push(animated: true)
    }
}
